<template>
  <div>
    <div
        style="display: flex; justify-content: space-between; align-items: center; width: 100%; border-bottom: 2px solid #cccccc; padding-bottom: 10px">
      <span style="font-size: 17px; color: #333333;">广告详情</span>
      <i class="el-icon-back" @click="handleBack()"
         style="font-size: 18px; color: deepskyblue; cursor: pointer;">返回</i>
    </div>
    <div style="width: 100%">
      <table style="width: 100%;margin-left: 20px;">
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">ID</td>
          <td>{{ splitAd.id.toString().padStart(9, '0') }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">广告标题<span style="color: red">*</span></td>
          <td>
            <div v-if="this.splitAd.isStatus !== 1">
              <el-input v-model="updateForm.adHeadline" style="width: 500px" placeholder="请输入广告标题"/>
              <span style="color: #cccccc;margin-left: 10px;font-size: small">广告标题长度不能超过40</span>
            </div>
            <div v-else-if="this.splitAd.isStatus === 1">
              {{ splitAd.adHeadline }}
            </div>
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">广告视频<span style="color: red">*</span></td>
          <td> 
            <div v-if="this.updateForm.video === ''">
            <el-upload drag
                       class="avatar-uploader el-upload--text"
                       :action="uploadUrl"
                       :multiple="false"
                       :show-file-list="true"
                       :on-success="onFileSuccess"
                       :before-upload="beforeUploadVideo"
                       :on-error="onFileError"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传mp4/flv/avi文件，且不超过200MB
              </div>
            </el-upload>
          </div>
            <div v-if="this.updateForm.video !== ''" style="display: flex; align-items: center;">
              <div v-if="updateForm.name !== ''">{{ updateForm.name }}&nbsp;&nbsp;<span style="color: #545c64;font-size: small"> 文件大小:{{
                  updateForm.size
                }}&nbsp;&nbsp; 视频时长:{{ updateForm.time }}秒</span></div>
              <div style="margin-left: 200px;display: flex">
                <el-upload
                    class="el-upload--text"
                    :action="uploadUrl"
                    :multiple="false"
                    :show-file-list="true"
                    :on-success="onFileSuccess"
                    :before-upload="beforeUploadVideo"
                    :on-error="onFileError"
                >
                  <div v-if="this.splitAd.isStatus !== 1">
                    <el-button type="text" style="color: #181818" class="el-upload__text">更换视频</el-button>&nbsp;&nbsp;|
                    <el-button type="text" style="color: #181818" @click="handleDeleteVideo()">删除</el-button>
                  </div>
                </el-upload>
              </div>
            </div>
          </td>

        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">状态</td>
          <td>
            {{ splitAd.isStatus === 0 ? '已生效' : splitAd.isStatus === 1 ? '已过期' : splitAd.isStatus === 2 ? '已上架' : splitAd.isStatus === 3 ? '已下架' : '未知' }}
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">创建时间</td>
          <td>{{ formatOpenDateTime(splitAd.createDateTime) }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">推送时间</td>
          <td>{{ formatOpenDateTime(splitAd.upDateTime) }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">失效时间</td>
          <td>{{ formatOpenDateTime(splitAd.downDateTime) }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;"></td>
          <td>
            <button v-if="this.splitAd.isStatus !== 1" class="el-button el-button--primary" @click="submit()" style="width: 80px;height: 40px">保存</button>
            <button class="el-button el-button--text" @click="updateStatus(2)"
                    style="height: 40px;color: #33cd95;border: 1px solid #33cd95;width: 80px;"
                    v-if="this.splitAd.isStatus === 3">上架
            </button>
            <button class="el-button el-button--primary" @click="updateUp=true"
                    style="height: 40px;width: 100px;"
                    v-if="this.splitAd.isStatus !== 3 && this.splitAd.isStatus !== 1">重新推送
            </button>
            <button class="el-button el-button--text" @click="updateStatus(3)"
                    style="height: 40px;color: #f56c6c;border: 1px solid #f56c6c;width: 80px;"
                    v-if="this.splitAd.isStatus === 0 || this.splitAd.isStatus === 2">下架
            </button>
            <button class="el-button el-button--text" @click="handleDelete()" v-if="this.splitAd.isStatus === 1"
                    style="height: 40px;color: red;border: 1px solid #f56c6c;width: 80px;">删除
            </button>
          </td>
        </tr>
      </table>

      <!--重新推送操作-->
      <el-dialog title="提示" :visible.sync="updateUp" width="500px">
        <div align="left">
          <el-button icon="el-icon-info" type="text" style="color: black">您确定重新推送该广告吗? 请设置推送时间~
          </el-button>
          <div style="margin: 20px">
            <el-form :model="updateUpForm" ref="updateUpForm" :rules="updateUpFormRules">
              <el-form-item prop="upDateTime">
                <el-date-picker
                    v-model="updateUpForm.upDateTime"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          <span style="color: lightgray;font-size: small">推送时间必须大于当前时间</span>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="newUp()">确 定</el-button>
          <el-button @click="updateUp = false; resetForm('updateUpForm')">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {findSplidAdById, updateSplitAd, updateStatus} from "@/api/ad/splitAdvertising"
import {serverUrl} from "@/utils/request";

export default {
  name: "SplitAdDetail",
  data() {
    return {
      updateUp: false,
      updateUpForm: {
        upDateTime: '',
      },
      uploadUrl: serverUrl + "/ad/oss/uploadOneFile",
      id: '',
      uploadVideo: false,
      splitAd: {
        id: '',
        adHeadline: '',
        video: '',
        time: '',
        name: '',
        size: '',
        isStatus: '',
        createDateTime: '',
        upDateTime: '',
        downDateTime: '',
      },
      updateForm: {
        id: '',
        adHeadline: '',
        video: '',
        time: '',
        name: '',
        size: '',
      },
      updateUpFormRules:{
        upDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('推送时间不能为空'));
              }
              const currentTime = new Date();
              currentTime.setHours(currentTime.getHours() + 1); // 可以设置为当前时间之后的时间，这里示例为当前时间1小时后
              if (value < currentTime) {
                callback(new Error('推送时间必须大于当前时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
    }
  },
  methods: {
    /*重置表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /*重新推送*/
    newUp() {
      this.$refs.updateUpForm.validate((valid) => {
        if (valid) {
          const data = {
            id: this.id,
            upDateTime: this.updateUpForm.upDateTime,
            isStatus: 0
          }
          updateStatus(data).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.updateUp = false;
              this.resetForm('updateUpForm');
              this.init();
            } else {
              this.$message({
                message: '操作失败',
                type: 'warning'
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    init() {
      findSplidAdById(this.id).then(result => {
        this.splitAd = result.data;
        this.updateForm.id = this.splitAd.id;
        this.updateForm.adHeadline = this.splitAd.adHeadline;
        this.updateForm.video = this.splitAd.video;
        this.updateForm.time = this.splitAd.time;
        this.updateForm.name = this.splitAd.name;
        this.updateForm.size = this.splitAd.size;
      }).catch(err => {
        console.log(err);
      })
    },
    updateStatus(val) {
      const data = {
        id: this.id,
        isStatus: val
      }
      updateStatus(data).then(result => {
        if (result.code === 200) {
          this.$message({
            message: '上架成功',
            type: 'success'
          })
          this.init();
        } else {
          this.$message({
            message: result.message,
            type: 'error'
          })
        }
      })
    },
    handleDelete(){
      const data = {
        id: this.id,
        isDel: 1
      }
      updateStatus(data).then(result => {
        if (result.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$router.go(-1);
        } else {
          this.$message({
            message: result.message,
            type: 'error'
          })
        }
      })
    },
    /*规范时间格式 年月日 时分秒*/
    formatOpenDateTime(date) {
      if (!date) return '--'; // 如果日期为空，则返回 '--'

      // 将日期转换为 Date 对象（如果是字符串的话）
      const d = date instanceof Date ? date : new Date(date);

      // 获取年月日时分秒
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hour = d.getHours().toString().padStart(2, '0');
      const minute = d.getMinutes().toString().padStart(2, '0');
      const second = d.getSeconds().toString().padStart(2, '0');

      // 返回格式化的日期时间字符串，例如 '2024-08-27 12:34:56'
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    handleBack() {
      this.$router.go(-1);
    },
    handleDeleteVideo() {
      this.updateForm.video = '';
      this.updateForm.name = '';
      this.updateForm.time = '';
      this.updateForm.size = '';
    },
    onFileError(file) {
      this.$message({
        message: '上传失败,请再次尝试',
        type: 'error'
      })
      console.log('error', file);
    },
    onFileSuccess(response, file) {
      this.updateForm.video = response;
      this.updateForm.name = file.name;
      this.updateForm.size = (file.size / (1024 * 1024)).toFixed(2);
      // 创建一个新的视频元素
      const video = document.createElement('video');

      // 创建一个文件URL
      const videoURL = URL.createObjectURL(file.raw);

      // 设置视频元素的源为文件URL
      video.src = videoURL;

      // 添加loadedmetadata事件监听器，以在元数据加载完成后获取时长
      video.addEventListener('loadedmetadata', () => {
        // 获取视频时长（以秒为单位）
        const duration = video.duration;
        this.updateForm.time = duration.toFixed(2);
      });
      // 开始加载视频元数据
      video.load();
    },
    beforeUploadVideo(file) {
      // 上传前的钩子函数，可以在这里进行文件类型和大小的校验
      const isVideo = file.type === 'video/mp4';
      if (!isVideo) {
        this.$message.error('只能上传mp4/flv/avi文件格式!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 200;
      if (!isLt5M) {
        this.$message.error('视频大小不能超过 200MB!');
        return false;
      }
      return true;
    },
    submit() {
      this.$confirm('确定要保存吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.updateForm.adHeadline === '') {
          this.$message({
            type: 'error',
            message: '请先填写广告标题!'
          });
          return;
        } else if (this.updateForm.adHeadline.length === 0) {
          this.$message({
            type: 'error',
            message: '广告标题不能为空!'
          });
          return;
        } else if (this.updateForm.adHeadline.length > 40) {
          this.$message({
            type: 'error',
            message: '广告标题长度不能超过40!'
          });
        }
        if (this.updateForm.video === '') {
          this.$message({
            type: 'error',
            message: '请先上传视频!'
          });
          return;
        }
        updateSplitAd(this.updateForm).then(result => {
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '保存成功!'
            });
            this.$router.go(-1);
          } else {
            this.$message({
              type: 'error',
              message: result.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消保存'
        });
      });
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this.init();
  },
  created() {
  },
}
</script>

<style scoped>

</style>
